/**
 * 该文件用于存储当前登录用户信息
 */
import { defineStore } from 'pinia'
import type { User } from '@/utils/dataType/UserModel.ts'
import { checkToken, updateUserAvatar, userLogin } from '@/services/api/user.ts'
import router from '@/router'
import { ElMessage } from 'element-plus'

export const useCurrentUserStore = defineStore('user', {
  state: () => ({
    loginUser: {
      status: 0, //状态为0为未登录状态
      infor: {} as User,
    },
    isLoading: false,
  }),
  getters: {
    isLoggedIn: (state) => state.loginUser.status === 1,
  },
  actions: {
    //登录 1.获得token 2.获取基本信息
    async userLogin(username: string, password: string, redirect: string = '/') {
      try {
        const res = await userLogin({ username, password })
        console.log('修改用户状态信息')
        this.loginUser.status = 1
        this.loginUser.infor = res.data
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user', JSON.stringify(this.loginUser))
        router.push({
          path: redirect,
          replace: true,
        })
      } catch (error) {
        console.error('[登录]:出错了->', error)
      }
    },
    //登出操作
    userLogout() {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      this.loginUser.status = 0
      this.loginUser.infor = {} as User
      ElMessage.info('已成功退出登录')
      router.push('/')
    },
    // //更新个人信息
    // async updateProfile() {},
    //刷新本地化登录
    async checkAnyStoreUser() {
      const token: string = localStorage.getItem('token')
      const user = JSON.parse(localStorage.getItem('user'))
      if (token != null && user != null) {
        //写一个验证token的方法
        try {
          const res = await checkToken({ token })
          if (res.code === 1) {
            this.loginUser.status = 1
            this.loginUser.infor = user.infor
            console.log('此时的用户信息为:', this.loginUser)
            ElMessage.success('本地记忆登录')
          }
        } catch (error) {
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          ElMessage.error(error)
          console.error('[本地化登录出错]:', error)
        }
      }
    },
    //更新头像信息
    async updateAvatar(fromData:FormData) {
      this.isLoading = true
      try {
        const res = await updateUserAvatar(fromData)
        this.loginUser.infor.avatar = res.data
        ElMessage.success('头像更新成功')
      } catch (error) {
        ElMessage.error('头像上传更新失败')
        console.error('头像失败', error)
      } finally {
        this.isLoading = false
      }
    },
  },
})
